package br.com.aquinoevasconcelos.servlets.modeloContrato;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import br.com.aquinoevasconcelos.fachada.Fachada;
import br.com.aquinoevasconcelos.modelos.Dados;
import br.com.aquinoevasconcelos.modelos.ModeloContrato;
import br.com.aquinoevasconcelos.user.UsuarioAdm;
import br.com.aquinoevasconcelos.util.Pastas;

/**
 * Servlet implementation class InserirModeloContrato
 */
@WebServlet("/InserirModeloContrato")
public class InserirModeloContrato extends HttpServlet {
	private static final long serialVersionUID = 1L;

	public InserirModeloContrato() {
		super();

	}

	protected void service(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		
    	Fachada fachada = Fachada.getInstancia();
    	String categoria = null;
    	String loginCliente = null;
    	Dados dados = new Dados(categoria, loginCliente);
    	ModeloContrato mc = new ModeloContrato();
    	UsuarioAdm adm = new UsuarioAdm();
    	
    	ArrayList<UsuarioAdm> usuAdm = new ArrayList<UsuarioAdm>();


    	HttpSession sessaoAdm = request.getSession();
    	adm = (UsuarioAdm) sessaoAdm.getAttribute("sessaoAdministrador");
    	
    	
    	
    	mc.setAdm(adm);
    	
        boolean isMultipart = ServletFileUpload.isMultipartContent(request);
        if(isMultipart) {
            try {
                FileItemFactory factory = new DiskFileItemFactory();
                ServletFileUpload upload = new ServletFileUpload(factory);
                java.util.List<FileItem> items = (java.util.List<FileItem>) upload.parseRequest(request);
                for(FileItem item : items) {
                    if(item.isFormField()) {
           
                        //se for um campo normal de form
                        response.getWriter().println("Form field");
                        response.getWriter().println("Name:"+item.getFieldName());
                        response.getWriter().println("Value:"+item.getString());
                        
                        if (item.getFieldName().equals("titulo")){
                        	System.out.println("entrou "+item.getString());
                          mc.setTitulo(item.getString());
                        }  
                        
          
                        else if (item.getFieldName().equals("categoria")){
                        	System.out.println("entrou "+item.getString());
                        	dados.categoria = item.getString();
                        	mc.setCategoria(item.getString());
                        	
                          
                            }
                 
                        
                        else{
                        	System.out.println("errooo"+item.getString());
                        }
                       
                        
                    }
                    
                    else {
                        //caso seja um campo do tipo file
                    	response.getWriter().println("NOT Form field");
                    	response.getWriter().println("Name:"+item.getFieldName());
                    	response.getWriter().println("FileName:"+item.getName());
                    	response.getWriter().println("Size:"+item.getSize());
                    	response.getWriter().println("ContentType:"+item.getContentType());
                    	
                    	File uploadedFile = new File(new Pastas().caminhoPrincipalModelo()+dados.categoria+"/"+item.getName());
                    	item.write(uploadedFile);
                    	
                        mc.setCaminhoArquivo(uploadedFile.getPath());
                    	fachada.atualizarADM(adm);
                    	fachada.inserirModeloContato(mc);
                    	
                     	response.sendRedirect("admin/novo_modelo_formulario.jsp?msg=sucesso");
                    	
                    }
                }
            } catch (Exception e) {
            	response.getWriter().println("ocorreu um problema ao fazer o upload: " + e.getMessage());
            	
    			RequestDispatcher rd = request.getRequestDispatcher("pagina_erro/erro.jsp");
    			rd.forward(request, response);
    			e.printStackTrace();
            }
 
        }
	
		
	}

	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		service(request, response);
	}

	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		service(request, response);

	}

}
